Shader "volumeFogVF1"
{
Properties
{
	_FogColor ("Fog Color", Color) = (0, 0.15, 0.115, 1)
    _FogDensity ("FogDensity", Range(0,0.1)) = 0.03
}
SubShader
{
	Tags { "Queue" = "Transparent" "RenderType"="Transparent"}

	Blend  SrcAlpha OneMinusSrcAlpha

    Pass{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag

#include "UnityCG.cginc"

sampler2D _CameraDepthTexture;

struct v2f
{
    float4 vertex : SV_POSITION;
    float2 uv : TEXCOORD0;
    float3 viewVec : TEXCOORD1;
    float4 scrPos : TEXCOORD2;
    float4 worldPos : TEXCOORD3;
};

fixed4 _FogColor;
float _FogDensity;

float4x4 _InverseProjectionMatrix;
float4x4 _InverseViewMatrix;

v2f vert (appdata_full v)
{
	v2f o;
    o.vertex =UnityObjectToClipPos(v.vertex);
	o.scrPos = ComputeGrabScreenPos(o.vertex);

    //计算相机空间中的像素方向（相机到像素的方向）
    //https://zhuanlan.zhihu.com/p/92315967
    //屏幕纹理坐标
    float4 screenPos = ComputeScreenPos(o.vertex);
    // NDC position
    float4 ndcPos = (screenPos / screenPos.w) * 2 - 1;
    // 计算至远屏幕方向
    float3 clipVec = float3(ndcPos.x, ndcPos.y, 1.0) * _ProjectionParams.z;
    o.viewVec = mul(unity_CameraInvProjection, clipVec.xyzz).xyz;

    o.worldPos = mul(unity_ObjectToWorld, v.vertex);

    return o;
}

float  cloudRayMarching(float3 startPos, float3 rayDir)
{
    float sum = 0;
    float3 testPoint = startPos;
    float threshold = 5;
    rayDir *= 0.2;
    for(int i=1; i< 300 ; i++){

        testPoint += rayDir;

        if( -threshold < testPoint.x  && testPoint.x < threshold &&  
         -threshold < testPoint.y  && testPoint.y < threshold &&  
          -threshold < testPoint.z  && testPoint.z < threshold )
        sum += _FogDensity;
    }

    return sum;
}

//计算世界空间坐标
// float4 GetWorldSpacePosition(float depth, float2 uv)
// {
//      // 屏幕空间 --> 视锥空间
//      float4 view_vector = mul(_InverseProjectionMatrix, float4(2.0 * uv - 1.0, depth, 1.0));
//      view_vector.xyz /= view_vector.w;
//      //视锥空间 --> 世界空间
//      float4x4 l_matViewInv = _InverseViewMatrix;
//      float4 world_vector = mul(l_matViewInv, float4(view_vector.xyz, 1));
//      return world_vector;
// }

fixed4 frag (v2f i) : SV_Target
{

    //采样获得深度值
    float depth = UNITY_SAMPLE_DEPTH(tex2Dproj(_CameraDepthTexture, i.scrPos));
    depth = Linear01Depth(depth);

    //获取像素相机屏幕坐标位置
    float3 viewPos = depth * i.viewVec;

    //Pixel world position
    //float3 worldPos = mul(UNITY_MATRIX_I_V, float4(viewPos, 1)).xyz;

    //float3 worldPos = GetWorldSpacePosition(depth, i.scrPos.xy);
    float3 worldPos = i.worldPos;

    float3 rayPos = _WorldSpaceCameraPos;

    float3 worldViewDir = normalize(worldPos - rayPos);

    //return fixed4(worldViewDir, 1);

    float FogDensity = cloudRayMarching(rayPos, worldViewDir);

    return _FogColor * FogDensity;
}

ENDCG
    }
}
    FallBack off
}